package net.tngou.crawler.lucene;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.lucene.search.BooleanClause.Occur;



/**
 * 
* @Description: jtdb主要的工具类，用于直接操作TngouDB
* @author tngou@tngou.net (www.tngou.net)
* @date 2015年6月17日 下午2:21:42
*
 */
public class TngouDBHelp {

	
	
	

//	protected static ResultSet response = new ResultSet();
	protected static LuceneManage luceneManage ;

	public TngouDBHelp() {
		luceneManage= LuceneManage.getInstance();
	}
	
	
	/**
	 * 
	* @Description:  创建表
	* @param  tableName  表名
	 */
	public boolean createTable(String tableName) {
		return luceneManage.createTable(tableName);	
	}
	
	
	/**
	 * 
	* @Description: 删除表
	* @param tableName    表名
	 */
	public boolean dropTable(String tableName) {
		
		return luceneManage.dropTable(tableName);	
	}
	
	
	/**
	 * 
	* @Description: 插入数据
	* @param  tableName  插入数据表
	* @param  fields    值
	* @throws
	 */
	public int insert(String tableName ,Field ...fields) {
	

		List<Field> list = Arrays.asList(fields);
		return luceneManage.add(list, tableName);
	}
	
	
	/**
	 * 
	* @Description: 插入数据
	* @param @param tableName
	* @param @param fields    设定文件
	* @return void    返回类型
	* @throws
	 */
	public int insert(String tableName ,Fields fields) {
	
		List<Field> list = fields.getList();
		Field[] fs = (Field[]) list.toArray(new Field[list.size()] ); 
		return insert( tableName ,fs);
		
	}
	
	/**
	 * 批量插入
	 * @param tableName
	 * @param list
	 * @return
	 */
	public int insert(String tableName ,List<Fields> list) {
		
		List<List<Field>> lists  = new ArrayList<>();
		for (Fields e : list) {
			lists.add(e.getList());
		}
		return luceneManage.adds(lists, tableName);
		
	}
	
	/**
	 * 
	* @Description: 查询数据
	* @param @param tableName  表名
	* @param @param sortField  排序
	* @param @param page  当前页
	* @param @param size  大小
	* @param @param fields 查询条件
	* @return Page    返回类型
	* @throws
	 */
	public Page select(String tableName ,int page,int size,Field ...fields) {
		
		 if(page < 0 || size < 0){page=1;size=1;}
		 int from = (page - 1) * size;
		 size = (size > 0) ? size : Integer.MAX_VALUE;
		  Occur[] flags=new Occur[fields.length];
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				switch (field.getType()) {
				case Text:
					flags[i]=Occur.SHOULD;
					break;
              case String:
             	 flags[i]=Occur.MUST;
					break;
				default:
					flags[i]=Occur.MUST;
					break;
				}
				
			}

		return luceneManage.get(from, size, fields,flags, null, tableName);
		
	}
	
	
	
	
	
	
	
	
	

  
}

